﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Windows;

namespace T03ChatServer
{
    class HandleClient
    {
        public Socket ClientSocket = null;
        public string clientNo = null;
        public Dictionary<string, Socket> clientList = null;

        public void StartListen(Socket ClientSocket, string clientNo, Dictionary<string, Socket> clientList)
        {
            this.ClientSocket = ClientSocket;
            this.clientNo = clientNo;
            this.clientList = clientList;
            Thread thread = new Thread(Chat);
            thread.IsBackground = true; 
            thread.Start();
        }
        public void Chat()
        {
            byte[] bytefromclient = new byte[4096];
            string datafromclient = null;
            byte[] bytesend = new byte[4096];
            string datasend = null;
            bool isListen = true;
            try
            {
                while (isListen)
                {
                    int len = ClientSocket.Receive(bytefromclient);
                    datafromclient = Encoding.UTF8.GetString(bytefromclient, 0, len);
                    if (!string.IsNullOrWhiteSpace(datafromclient))
                    {
                        datafromclient = datafromclient.Substring(0, datafromclient.LastIndexOf("$"));
                        if (!string.IsNullOrWhiteSpace(datafromclient))
                        { 
                            BroadCast.BroadMessage(datafromclient, clientNo, clientList, BroadCast.CLIENT_MSG);
                            datasend = clientNo + datafromclient + "\t\t" + DateTime.Now;
                            File.AppendAllText("D:\\CLIENT_MSG.txt", datasend);
                        }
                        else
                        {
                            //主动关闭连接
                            clientList.Remove(clientNo);
                            ClientSocket.Close();
                            ClientSocket = null;
                            isListen = false;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                clientList.Remove(clientNo);
                ClientSocket.Close();
                ClientSocket = null;
                isListen = false;
                Debug.WriteLine(e.ToString());
            }
        }
    }
}
